package com.ddc.study.user;

import android.content.Context;
import android.content.SharedPreferences;

import com.ddc.study.entity.User;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * Created on 2018/8/3.
 *
 * @author lshun
 * @version 1.0
 */
public class UserManager {
    private static final String PREFS_KEY = "UserPrefs";

    private static final String KEY_COLLECT_IDS = "collectIds";
    private static final String KEY_EMAIL = "email";
    private static final String KEY_ICON = "icon";
    private static final String KEY_ID = "id";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_TYPE = "type";

    @Nullable
    private User mUser;
    private final Context mContext;

    private UserManager(@NonNull Context context) {
        mContext = context.getApplicationContext();

        //user信息持久化
        SharedPreferences sp = mContext.getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE);
        if (!sp.contains(KEY_COLLECT_IDS)) return;
        if (!sp.contains(KEY_EMAIL)) return;
        if (!sp.contains(KEY_ICON)) return;
        if (!sp.contains(KEY_ID)) return;
        if (!sp.contains(KEY_USERNAME)) return;
        if (!sp.contains(KEY_TYPE)) return;

        mUser = new User();
        String idStr = sp.getString(KEY_COLLECT_IDS, null);
        //idStr为null  ->  mUser.collectIds为null
        if (idStr != null && !idStr.isEmpty()) {
            //string[] 转 int[]
            String[] temp = idStr.split(",");
            int len = temp.length;
            int[] ids = new int[len];
            for (int i = 0; i < len; i++) {
                ids[i] = Integer.parseInt(temp[i]);
            }
            mUser.collectIds = ids;
        }
        mUser.email = sp.getString(KEY_EMAIL, null);
        mUser.icon = sp.getString(KEY_ICON, null);
        mUser.id = sp.getInt(KEY_ID, -1);
        mUser.username = sp.getString(KEY_USERNAME, null);
        mUser.type = sp.getInt(KEY_TYPE, -1);
    }

    /**
     * Get the user manager instance
     *
     * @param context the application context
     * @return the user manager instance
     */
    public static UserManager getInstance(@NonNull Context context) {
        //TODO 使用单例实现
        return new UserManager(context);
    }

    @Nullable
    public User getUser() {
        return mUser;
    }

    public void setUser(@Nullable User user) {
        mUser = user;

        //user信息持久化
        SharedPreferences sp = mContext.getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        if (mUser == null) {
            editor.clear();
        } else {
            if (mUser.collectIds == null) {
                editor.putString(KEY_COLLECT_IDS, null);
            } else {
                StringBuilder builder = new StringBuilder();
                for (int i = 0, len = mUser.collectIds.length; i < len; i++) {
                    if (i != 0) builder.append(",");
                    builder.append(mUser.collectIds[i]);
                }
                editor.putString(KEY_COLLECT_IDS, builder.toString());
            }
            editor.putString(KEY_EMAIL, mUser.email);
            editor.putString(KEY_ICON, mUser.icon);
            editor.putInt(KEY_ID, mUser.id);
            editor.putString(KEY_USERNAME, mUser.username);
            editor.putInt(KEY_TYPE, mUser.type);
        }
        editor.apply();

        notifyUserChange(user);
    }

    private void notifyUserChange(User user) {
        if (mObservers == null) return;
        for (UserObserver observer : mObservers) {
            observer.onUserChanged(user);
        }
    }

    public boolean isLoggedIn() {
        return mUser != null && mUser.username != null;
    }

    public void logOut() {
        setUser(null);
    }

    private List<UserObserver> mObservers;

    public void observe(@NonNull UserObserver observer) {
        if (mObservers == null) mObservers = new ArrayList<>();
        if (!mObservers.contains(observer)) {
            mObservers.add(observer);
        }
    }

    public void removeObserver(@NonNull UserObserver observer) {
        if (mObservers != null) {
            mObservers.remove(observer);
        }
    }

    public interface UserObserver {
        void onUserChanged(@Nullable User user);
    }
}
